package com.hd.crdao.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.activity.CheckActivity;
import com.hd.crdao.activity.GetMoneyActivity;
import com.hd.crdao.activity.MessageCenterActivity;
import com.hd.crdao.activity.MyAccountActiviy;
import com.hd.crdao.activity.MyCarSourceActivity;
import com.hd.crdao.activity.MyShopActivity;
import com.hd.crdao.activity.NewLoanCarActivity;
import com.hd.crdao.activity.NewOrderActivity;
import com.hd.crdao.activity.OpenShopCertificationActivity;
import com.hd.crdao.activity.ReleaseActivity;
import com.hd.crdao.activity.RepairQueryActivity;
import com.hd.crdao.activity.SetAmountActivity;
import com.hd.crdao.activity.SettingsActivity;
import com.hd.crdao.activity.UserActivity;
import com.hd.crdao.base.BaseFragment;
import com.hd.crdao.bean.CarBusinessInfoBean;
import com.hd.crdao.bean.MessageBean;
import com.hd.crdao.bean.RecAccountStatusBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.StringUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/5/10 0010
 */
public class MyFragment extends BaseFragment implements View.OnClickListener {


    TextView mUserProperties;
    ImageView mHeadPic;
    TextView mTvName;
    ImageView mArrow;
    ImageView mMessage;
    ImageView mSettings;
    TextView mCreaditSum;
    TextView mLeakSum;
    TextView mTobuycar;
    TextView mOrdercheck;
    TextView mRepairquery;
    TextView mIllegalquery;
    TextView mDischargequery;
    TextView mFreeopen;
    TextView mTel;
    TextView mMyCarSource;
    TextView myOrder;
    TextView mLoanCar;
    TextView mWannaGathering;

    public LinearLayout mMyAccount;
    public CarBusinessInfoBean.CarBusinessBean carBusinessInfo;
    public CarBusinessInfoBean carBusinessInfoBean;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;

    }

    @Override
    protected void initView() {

        mUserProperties = (TextView) mViewRoot.findViewById(R.id.user_properties);
        mHeadPic = (ImageView) mViewRoot.findViewById(R.id.head_pic);
        mTvName = (TextView) mViewRoot.findViewById(R.id.tvName);
        mArrow = (ImageView) mViewRoot.findViewById(R.id.arrow);
        mMyCarSource = (TextView) mViewRoot.findViewById(R.id.mycarsource);
        mLoanCar = (TextView) mViewRoot.findViewById(R.id.loancar);
        myOrder = (TextView) mViewRoot.findViewById(R.id.neworder);
        mMyCarSource = (TextView) mViewRoot.findViewById(R.id.mycarsource);
        mMessage = (ImageView) mViewRoot.findViewById(R.id.message);
        mSettings = (ImageView) mViewRoot.findViewById(R.id.settings);
        mCreaditSum = (TextView) mViewRoot.findViewById(R.id.creaditSum);
        mLeakSum = (TextView) mViewRoot.findViewById(R.id.leakSum);
        mTobuycar = (TextView) mViewRoot.findViewById(R.id.tobuycar);
        mOrdercheck = (TextView) mViewRoot.findViewById(R.id.ordercheck);
        mRepairquery = (TextView) mViewRoot.findViewById(R.id.repairquery);
        mIllegalquery = (TextView) mViewRoot.findViewById(R.id.illegalquery);
        mDischargequery = (TextView) mViewRoot.findViewById(R.id.dischargequery);
        mFreeopen = (TextView) mViewRoot.findViewById(R.id.freeopen);
        mTel = (TextView) mViewRoot.findViewById(R.id.tel);
        mMyAccount = (LinearLayout) mViewRoot.findViewById(R.id.myaccount);
        mWannaGathering = (TextView) mViewRoot.findViewById(R.id.wannagathering);
    }

    @Override
    protected void initListener() {
        mUserProperties.setOnClickListener(this);
        mHeadPic.setOnClickListener(this);
        mTvName.setOnClickListener(this);
        mArrow.setOnClickListener(this);
        mMessage.setOnClickListener(this);
        mSettings.setOnClickListener(this);
        mCreaditSum.setOnClickListener(this);
        mLeakSum.setOnClickListener(this);
        mTobuycar.setOnClickListener(this);
        mOrdercheck.setOnClickListener(this);
        mRepairquery.setOnClickListener(this);
        mIllegalquery.setOnClickListener(this);
        mDischargequery.setOnClickListener(this);
        mFreeopen.setOnClickListener(this);
        mTel.setOnClickListener(this);
        myOrder.setOnClickListener(this);
        mMyCarSource.setOnClickListener(this);
        mLoanCar.setOnClickListener(this);
        mMyAccount.setOnClickListener(this);
        mWannaGathering.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        final Dialog dialog = StyledDialog.buildLoading().setActivity(getActivity()).show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String businessid = SPUtils.getString(Config.businessId, "");
                OkHttpUtils.post().url(Constants.GETCARBUSINESS_URL)
                        .addParams("appFlag", "true")
                        .addParams("id", businessid).build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("网络开了个小差");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ALog.d(response);
                        carBusinessInfoBean = new Gson().fromJson(response, CarBusinessInfoBean.class);
                        if (carBusinessInfoBean.getSuccess() == 0) {
                            carBusinessInfo = carBusinessInfoBean.getCarBusiness();
                            setSomeParams();
                            SPUtils.saveString(Config.userId, carBusinessInfo.getUser().getId());
                            SPUtils.saveString(Config.cbPhoneNumber, carBusinessInfo.getCbContphone());
                            SPUtils.saveString(Config.cbXY, carBusinessInfo.getCbXy());
                            SPUtils.saveString(Config.areaId, carBusinessInfo.getArea().getId());
                            SPUtils.saveString("redisplayAddress", carBusinessInfo.getAllAreaName() + carBusinessInfo.getCbAddress());

                        }
                    }
                });
                StyledDialog.dismiss(dialog);
            }
        }, 1000);


    }

    private void setSomeParams() {
        //用户名
        mTvName.setText(carBusinessInfo.getCbContacts());
        //车商
        String[] userType = getResources().getStringArray(R.array.userType);
        int usertype = carBusinessInfo.getUser().getUserType();
        mUserProperties.setText(userType[usertype] + "---" + carBusinessInfo.getArea().getName());

        if (carBusinessInfo.getCbSt() == 2) {       //2表示已经审核通过
            mCreaditSum.setText(StringUtils.doubleToString(carBusinessInfo.getCbTotalamt()));
            double value = carBusinessInfo.getCbTotalamt() - carBusinessInfo.getCbAlreadyamt();
            mLeakSum.setText(StringUtils.doubleToString(value));
        } else {
            mCreaditSum.setText("0.0");
            mLeakSum.setText("0.0");
        }

        String ImageUrl = carBusinessInfo.getCbImage();
        if (TextUtils.isEmpty(ImageUrl)) {
            mHeadPic.setImageResource(R.drawable.logo_moren_2x);
        } else {
            GlideImageUtils.loadImage(Constants.IMAGEURL + ImageUrl,R.drawable.logo_moren_2x,true,mHeadPic);
        }
        //显示免费开店还是显示我的店铺逻辑
        if (carBusinessInfo.getStoreAuthstatus() != 4) {
            Drawable drawable = getResources().getDrawable(R.drawable.new_3x);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mFreeopen.setCompoundDrawables(null, drawable, null, null);
            mFreeopen.setText("免费开店");
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.newshop);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mFreeopen.setCompoundDrawables(null, drawable, null, null);
            mFreeopen.setText("我的店铺");
        }
        boolean wannaGathering = SPUtils.getBoolean(Config.wannaGatheringIsNew, true);
        Drawable drawable = getResources().getDrawable(wannaGathering ? R.drawable.recive_new : R.drawable.recei_2x);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mWannaGathering.setCompoundDrawables(null, drawable, null, null);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_properties:
                tochangePicActivity();//跳转到更改个人信息
                break;
            case R.id.head_pic:
                tochangePicActivity();//跳转到更改个人信息
                //startActivity(new Intent(UIUtils.getContext(), ChangeHeadPicActivity.class));
                break;
            case R.id.tvName:
                tochangePicActivity();//跳转到更改个人信息
                break;
            case R.id.arrow:
                tochangePicActivity();//跳转到更改个人信息
                break;
            case R.id.message:
                startActivity(new Intent(UIUtils.getContext(), MessageCenterActivity.class));
                break;
            case R.id.settings:
                startActivity(new Intent(UIUtils.getContext(), SettingsActivity.class));
                break;
            case R.id.mycarsource:
                startActivity(new Intent(UIUtils.getContext(), MyCarSourceActivity.class));
                break;
            case R.id.neworder:
                startActivity(new Intent(UIUtils.getContext(), NewOrderActivity.class));
                break;
            case R.id.loancar:
                startActivity(new Intent(UIUtils.getContext(), NewLoanCarActivity.class));
                break;

            case R.id.tobuycar:
                startActivity(new Intent(UIUtils.getContext(), ReleaseActivity.class));
                break;
            case R.id.ordercheck:
                startActivity(new Intent(UIUtils.getContext(), CheckActivity.class));
                break;
            case R.id.repairquery:
                startActivity(new Intent(UIUtils.getContext(), RepairQueryActivity.class));
                break;
           /* case R.id.illegalquery:
                MyToast.show("违章查询,敬请期待");
                break;*/
            case R.id.dischargequery:
                MyToast.show("排放查询,敬请期待");
                break;
            case R.id.freeopen:
                if (carBusinessInfo != null && carBusinessInfo.getStoreAuthstatus() != 4) {
                    Intent intent = new Intent(UIUtils.getContext(), OpenShopCertificationActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("userInfoBean", carBusinessInfo);
                    intent.putExtra("userinfo", bundle);
                    startActivity(intent);
                } else {
                    startActivity(new Intent(UIUtils.getContext(), MyShopActivity.class));
                }

                break;
            case R.id.tel:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + getResources().getString(R.string.companyTelephone)));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.myaccount:
                startActivity(new Intent(UIUtils.getContext(), MyAccountActiviy.class));
                break;
            case R.id.wannagathering:
                getStatus();
                break;
            default:
                break;


        }
    }

    public void getStatus() {
        String businessId = SPUtils.getString(Config.businessId, "");
        OkHttpUtils.post().url(Constants.GET_RECACCOUNT_STATUS_URL).addParams("carBusinessId", businessId).addParams("sign", Constants.SIGN)
                .build().execute(new StringCallback() {
                                     @Override
                                     public void onError(Call call, Exception e, int id) {
                                         MyToast.show("网络开了个小差");
                                     }

                                     @Override
                                     public void onResponse(String response, int id) {
                                         ALog.d(response);
                                         MessageBean messageBean = new Gson().fromJson(response, MessageBean.class);
                                         SPUtils.saveBoolean(Config.wannaGatheringIsNew, false);
                                         if (messageBean.getSuccess() == 0) {
                                             RecAccountStatusBean recAccountStatusBean = new Gson().fromJson(response, RecAccountStatusBean.class);
                                             double crRate = recAccountStatusBean.getCbRecaccount().getCrRate();
                                             double crT1rate = recAccountStatusBean.getCbRecaccount().getCrT1rate();
                                             Intent intent = new Intent(UIUtils.getContext(), SetAmountActivity.class);
                                             intent.putExtra("crRate", new String[]{String.valueOf(crRate) + "%", String.valueOf(crT1rate) + "%"});
                                             startActivity(intent);
                                         } else {
                                             startActivity(new Intent(UIUtils.getContext(), GetMoneyActivity.class));
                                         }


                                     }
                                 }
        );
    }


    private void tochangePicActivity() {
        Intent intent = new Intent(UIUtils.getContext(), UserActivity.class);
        intent.putExtra("userinfobean", carBusinessInfo);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 102 && data != null) {
            try {
                byte[] headpics = data.getByteArrayExtra("headpic");
                byte[] encodeByte = Base64.decode(headpics, Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(headpics, 0, encodeByte.length);
                mHeadPic.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.getMessage();
            }
            /*String headimagespath = data.getStringExtra("headimagespath");
            ALog.d("我是一个头像的路径"+headimagespath);*/
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onPause() {
        super.onPause();
        ALog.d("pause");
    }

    @Override
    public void onStart() {
        initData();
        super.onStart();

    }

}
